﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using yafc.Interface.Api;
using System.Net;
using System.IO;

namespace Fanfou.Api
{
	class SendMsg : IApi
	{
		public ApiResults execute(ApiArgs Args)
		{
			HttpWebRequest request = null;
			HttpWebResponse response = null;

			if (Args.GetType() != typeof(SendArgs))
			{
				throw new Exception("PostMsg.execute(): Expecting arguments of type SendArgs but got " + Args.GetType().ToString());
			}
			SendArgs args = (SendArgs)Args;

			// Checking parameters
			if (args.username.Length == 0 || args.password.Length == 0)
			{
				throw new Exception("Login.execute(): Username or password shouldn't be empty.");
			}

			if (args.text.Length == 0)
			{
				SendResults skip = new SendResults();
				skip.status = System.Net.HttpStatusCode.OK;
			}

			// Sending request
			request = (HttpWebRequest)WebRequest.Create(URL.PostMsg);
			request.ContentType = "application/x-www-form-urlencoded";
			request.Method = "POST";
			request.ServicePoint.Expect100Continue = false;
			request.Headers.Add("Authorization", "Basic " + Args.authorization);

			// http request POST data
			string content = "status=" + args.text + "&source=yafc";
			byte[] raw = Encoding.UTF8.GetBytes(content);
			request.ContentLength = raw.Length;
			Stream stream = request.GetRequestStream();
			stream.Write(raw, 0, raw.Length);
			stream.Close();

			try
			{
				response = (HttpWebResponse)request.GetResponse();
			}
			catch (WebException ex)
			{
				response = (HttpWebResponse)ex.Response;
			}
			catch (Exception)
			{
			}

			SendResults results = new SendResults();
			if (response != null)
			{
				results.status = response.StatusCode;
				response.Close();
			}
			else
			{
				results.status = HttpStatusCode.RequestTimeout;
			}
			return results;
		}
	}
}
